# 解压可迭代对象赋值给多个变量

def drop_first_last(grades):
    first, *middle, last = grades

    return args(middle)


record = ('David', 'dave@example.com', '777-555-333', '111-222-333')

name, email, *phone_number = record #*用来获取剩余的全部变量值,不管有没有电话号码信息，phone_number始终是列表类型

print(name, email, phone_number)

records = [
    ('foo', 1, 2),
    ('bar', 'hello'),
    ('foo', 3, 4),
]

# 遍历迭代器的时候使用
def do_foo(x, y):
    print('foo', x, y)


def do_bar(s):
    print('bar', s)

for tag, *args in records:
    if tag == 'foo':
        do_foo(*args)
    elif tag == 'bar':
        do_bar(*args)

# 星号解压语法在字符串中的操作,分割字符串

line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'
uname, *fields, homedir, sh = line.split(':')

print(uname, fields, homedir, sh)

# 解压后丢弃一部分值
record = ('ACMC', 50, 123, 45, (12, 33, 2012))
name, *_, (*_, year) = record
print(name, year)

# 用分割语法实现递归算法
def sum1(items):
    head, *tail = items
    return head + sum(tail) if tail else head # 可以理解为是一个'倒装句'。

items = [1, 10, 7, 4, 5, 9]
print(sum1(items))

# collections 中的 deque
# deque(maxlen=N) 构造函数会新建一个固定大小的队列，当新的元素加入并且这个队列已满时，最老的元素会自动被移除
from collections import deque
q = deque(maxlen=3)
q.append(1)
q.append(2)
q.append(3)
print(q)
q.append(4)
print(q)
# deque也可以当做队列来用，如果不传入maxlen则是一个无限的队列，可以从队头或队尾插入或删除元素
# 注意：在队列两端插入或删除的时间复杂度是O（1）， 而在列表开头插入或删除复杂度是O（N）
q = deque()
q.append(1)
q.append(2)
q.append(3)
print(q)
q.appendleft(4)
print(q)
print(q.pop())
print(q)
print(q.popleft())
print(q)

# 查找最大或最小的N个元素, 用到了heapq模块的两个函数：nlargest()和nsmallest()
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums))
print(heapq.nsmallest(3, nums))

portfolio = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {'name': 'FB', 'shares': 200, 'price': 21.09},
    {'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}
]

cheap = heapq.nsmallest(3, portfolio, key=lambda s:s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s:s['price'])
print(cheap)
print(expensive)
#堆重要的特性就是heap[0]永远是最小的，通过heapq.heappop()方法获取到,一个一个的弹出
# heapify排序
heapq.heapify(nums)
print(nums)
print(heapq.heappop(nums))
print(heapq.heappop(nums))
print(heapq.heappop(nums))

print(sorted(nums)[:5])

#只查找一个最大或者最小的元素，则使用max（）min（）
print()

# 在python中 None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False
print(not None, not False, not '', not 0, not [], not {}, not ())

# is 和 ==的区别在于 is判断两个对象是否是同一个对象，即地址是否相同，== 只是判断值是否相等
list1 = [1, 2, 3]

list2 = [1, 2, 3]

print(list1 == list2)  #true

print(list1 is list2)  #false

# 如果比较相同的对象实例，is总是返回True 而 == 最终取决于 "eq()"
class foo(object):
    def __eq__(self, other):
        return True


f = foo()
y = foo()

print(f == None)  # true 因为__eq__是true
print(f is None)
print(f is y)

